package com.album.web.controller;

import com.album.web.util.Result;
import com.alibaba.fastjson.JSON;
import com.album.common.cbb.DateUtil;
import com.album.common.cbb.RestResult;
import com.album.web.anno.MyLog;
import com.album.web.api.IAlbumService;
import com.album.web.api.IFileService;
import com.album.web.api.IFiletransferService;
import com.album.web.api.IOperationLogService;
import com.album.web.util.OperationLogUtil;
import com.album.web.domain.AlbumBean;
import com.album.web.domain.FileBean;
import com.album.web.domain.UserBean;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/album")
public class AlbumController {
    /**
     * 当前模块
     */
    public static final String CURRENT_MODULE = "相册管理";
    @Resource
    IAlbumService albumService;
    @Resource
    IFileService fileService;
    @Resource
    IFiletransferService filetransferService;
    @Resource
    IOperationLogService operationLogService;

    /**
     * @return
     */
    @RequestMapping(value = "/albumindex")
    public ModelAndView essayIndex() {
        ModelAndView mv = new ModelAndView("/album/albumIndex.html");
        return mv;
    }

    @RequestMapping(value = "/myAlbumindex")
    public ModelAndView myAlbumindex() {
        ModelAndView mv = new ModelAndView("/album/myAlbumIndex.html");
        return mv;
    }

    /**
     * 添加相册
     *
     * @param albumBean
     * @return
     */
    @RequestMapping(value = "/addalbum", method = RequestMethod.POST)
    @MyLog(operation = "添加相册", module = CURRENT_MODULE)
    public String addAlbum(HttpServletRequest request, AlbumBean albumBean) {
        RestResult<String> restResult = new RestResult<String>();
        UserBean sessionUserBean = (UserBean) SecurityUtils.getSubject().getPrincipal();

        if (sessionUserBean == null) {
            restResult.setSuccess(false);
            restResult.setErrorMessage("用户没有登录");
            return JSON.toJSONString(restResult);
        }
        albumBean.setUserid(sessionUserBean.getUserId());

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        albumBean.setCreatetime(df.format(new Date()));//设置创建相册的时间时间

        int albumid = albumService.insertAlbum(albumBean);

        FileBean fileBean = new FileBean();
        fileBean.setFilename(albumBean.getAlbumname());
        fileBean.setUploadtime(DateUtil.getCurrentTime());

        fileBean.setFilepath("/我的相册/");
        fileBean.setIsdir(1);
        fileBean.setUserid(sessionUserBean.getUserId());
        fileBean.setAlbumid(albumBean.getAlbumid());
        fileService.insertFile(fileBean);

        restResult.setSuccess(true);
        restResult.setData("创建成功");
        operationLogService.insertOperationLog(
                OperationLogUtil.getOperationLogObj(request, "成功", CURRENT_MODULE, "创建相册", "创建相册成功"));
        return JSON.toJSONString(restResult);
    }

    /**
     * 删除相册
     *
     * @return
     */
    @RequestMapping(value = "/deleteAlbum", method = RequestMethod.POST)
    @MyLog(operation = "删除相册", module = CURRENT_MODULE)
    public Object deleteAlbum(@RequestParam Integer albumid) {
        RestResult<String> restResult = new RestResult<String>();
        AlbumBean albumBean = new AlbumBean();
        albumBean.setAlbumid(albumid);
        albumService.deleteAlbum(albumBean);
        UserBean sessionUserBean = (UserBean) SecurityUtils.getSubject().getPrincipal();
        List<FileBean> fileList = fileService.selectFileByAlbumId(albumBean);
        filetransferService.deleteImageByAlbum(albumBean);
        int deleteFileCount = 0;
        restResult.setSuccess(true);
        restResult.setData("删除相册部分成功");

        if (deleteFileCount == fileList.size()) {
            restResult.setData("删除相册成功");
        }

        return JSON.toJSONString(restResult);
    }

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 修改相册
     *
     * @param albumBean
     * @return
     */
    @RequestMapping(value = "/updatealbum", method = RequestMethod.POST)
    @MyLog(operation = "修改相册", module = CURRENT_MODULE)
    public String updateAlbum(AlbumBean albumBean) {
        RestResult<String> restResult = new RestResult<String>();
        UserBean sessionUserBean = (UserBean) SecurityUtils.getSubject().getPrincipal();

        FileBean fileBean = fileService.selectDirFileByAlbumid(albumBean);

        if (fileBean == null) {
            fileBean = new FileBean();
            fileBean.setAlbumid(albumBean.getAlbumid());
            fileBean.setFilename(albumBean.getAlbumname());
            fileBean.setUploadtime(DateUtil.getCurrentTime());

            fileBean.setFilepath("/我的相册/" + albumBean.getAlbumname() + "/");
            fileBean.setIsdir(1);
            fileBean.setUserid(sessionUserBean.getUserId());
            fileService.insertFile(fileBean);
        } else {
            fileBean.setFilename(albumBean.getAlbumname());
            fileBean.setFilepath("/我的相册/" + albumBean.getAlbumname() + "/");
            fileBean.setUploadtime(DateUtil.getCurrentTime());
            fileService.updateFile(fileBean);
        }


        jdbcTemplate.update("UPDATE album\n" +
                        "        SET albumname = ?, createtime = ?, albumintro = ?, albumpower = ?\n" +
                        "        , address = ?\n" +
                        "        WHERE albumid = ?", albumBean.getAlbumname(), albumBean.getCreatetime(), albumBean.getAlbumintro(),
                albumBean.getAlbumpower(), albumBean.getAddress(), albumBean.getAlbumid());


        restResult.setSuccess(true);
        restResult.setData("修改相册成功");
        return JSON.toJSONString(restResult);
    }

    /**
     * 获取用户的所有相册列表
     *
     * @return
     */
    @RequestMapping(value = "/getalbumlist")
    public String getAlbumList() {
        RestResult<List<AlbumBean>> restResult = new RestResult<List<AlbumBean>>();
        UserBean sessionUserBean = (UserBean) SecurityUtils.getSubject().getPrincipal();
//        if (sessionUserBean == null) {
//            restResult.setSuccess(false);
//            restResult.setErrorMessage("用户没有登录");
//            return JSON.toJSONString(restResult);
//        }

        List<AlbumBean> albumList = albumService.getAlbumListByUser(sessionUserBean);
        List<AlbumBean> albumListTotal = albumService.getAlbumListTotal();

        for (int i = 0; i < albumList.size(); i++) {
            for (int j = 0; j < albumListTotal.size(); j++) {
                if (albumList.get(i).getAlbumid() == albumListTotal.get(j).getAlbumid()) {
                    albumList.get(i).setPrimarirycountTotal(albumListTotal.get(j).getPrimarirycount());
                }
            }
        }

        Collections.sort(albumList, (o1, o2) -> {
            if (o1.getPrimarirycountTotal() < o2.getPrimarirycountTotal()) { return 1; }
            if (o1.getPrimarirycountTotal() == o2.getPrimarirycountTotal()) { return 0; }
            return -1;
        });

        restResult.setData(albumList);
        restResult.setSuccess(true);
        return JSON.toJSONString(restResult);
    }

    @RequestMapping(value = "/getMyAlbumlist")
    public String getMyAlbumlist(String address,String begin,String end) {
        RestResult<Map<String, Object>> restResult = new RestResult<>();
        UserBean sessionUserBean = (UserBean) SecurityUtils.getSubject().getPrincipal();
        if (sessionUserBean == null) {
            restResult.setSuccess(false);
            restResult.setErrorMessage("用户没有登录");
            return JSON.toJSONString(restResult);
        }
        sessionUserBean.setAddress(address);
        sessionUserBean.setBegin(begin);
        sessionUserBean.setEnd(end);
        List<AlbumBean> albumList = albumService.getMyAlbumlist(sessionUserBean);
        Map<String, Object> map = new HashMap<>();
        map.put("albumList", albumList);
        map.put("begin", StringUtils.isNotBlank(begin) ? begin : "");
        map.put("end", StringUtils.isNotBlank(end) ? end : "");
        restResult.setData(map);
        restResult.setSuccess(true);
        return JSON.toJSONString(restResult);
    }


    @ResponseBody
    @RequestMapping(value = "/listByCreateTime")
    public Result listByCreateTime(AlbumBean albumBean) {
        return new Result(albumService.listByCreateTime(albumBean));
    }
}

